package me.jzn.alib.utils;

import android.os.Handler;
import android.os.Looper;

/**
 * 用来在后台向主线程切换，类似于AndroidSchedulers.mainThread方法。
 * 本方法用来主要做不考虑生命周期的延时，同时作为RxJava的简易版，在没有rxjava的时候可方便的使用.
 */
public class MainThreadUtil {
	private static Handler sMainLooperHandler;

	private MainThreadUtil() {
	}

	private static final void init() {
		if (sMainLooperHandler == null) {
			sMainLooperHandler = new Handler(Looper.getMainLooper());
		}
	}

	public static final boolean isInMainThread() {
		return Looper.myLooper() == Looper.getMainLooper();
	}

	public static void post(Runnable r) {
		if (isInMainThread()) {
			r.run();
			return;
		}
		init();
		sMainLooperHandler.post(r);
	}

	public static void postDelayed(Runnable r) {
		init();
		sMainLooperHandler.post(r);
	}

	public static void postDelayed(Runnable r, long delayed) {
		init();
		sMainLooperHandler.postDelayed(r, delayed);
	}
}
